//
//  APPTransactionPair.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/6/28.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
@objc protocol TransactionPairDelegate:class {
    @objc optional func requestSuccess(_ data: [String : Any]?) //网络请求成功
    @objc optional func requestFail() //网络请求失败
}
class APPTransactionPair: NSObject {
    static let `default` = APPTransactionPair()
    
    var sysmbol: String = ""
    
    var sysmbols: [String] = []
    
    weak var delegate:TransactionPairDelegate?
    
    var failNumber:Int = 0 //失败次数
    
    //开放的币种数据
    var pairName:[String:[String]] = [:]
    //历史全部币种数据
    var historyPairName:[String:[String]] = [:]
    ///币币全部币种数据
    var coinPairName:[String:[String]] = [:]
    //支持币币交易数据源
    var coinPairInfo:[String:[CoinRegularModel]] = [:]
    
    //交易对数据源
    var pairDic:[String:[MarketCoinModel]] = [:]
    
    //币币对数据源
    var coinPairDic:[String:[MarketCoinModel]] = [:]
    
    //选中数字货币名称
    var selectCoinName:String = ""
    
    //币币选中的交易对 默认第一个
    var selectPairModel:MarketCoinModel = MarketCoinModel()
    //杠杆选中的交易对 默认第一个
    var leverPairModel:MarketCoinModel = MarketCoinModel()
    
    var isRequestFail:Bool = true //网络请求失败 点击重新刷新
    var isRequestIng:Bool = false //网络请求中
    
    ///获取首页币对信息
    private lazy var marketCoinApi: MarketCoinRequest = {
        let api = MarketCoinRequest()
        api.isPairAll = true
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    override init() {
        super.init()
    }
    
    func startPair() {
        self.loadCoin()

    }
    func loadCoin() {
        isRequestIng = true
        self.marketCoinApi.loadData()
    }
    
    
    
    /// 通过币种名称获取对应的交易对数组
    ///
    /// - Parameter coinName: 币种名称
    /// - Returns: 交易对数组
    func archivePairArray(coinName:String) -> [MarketCoinModel] {
        if APPTransactionPair.default.pairDic[coinName] != nil {
            let nameArr = coinPairName[coinName]
            var dataArr:[MarketCoinModel] = []
            for model in APPTransactionPair.default.pairDic[coinName]! {
                if (nameArr?.contains(model.name))! {
                    dataArr.append(model)
                }
            }
            
           return dataArr
        }
        return []
    }
    
    
    
    
    /// 订阅推送
    ///
    /// - Parameter key: 数字货币名称
    func subscribe(key:String) {
        if key.count == 0 {
            return
        }
      
        let dataArray = pairName[key]
        if (dataArray?.count)! <= 0 {
            return
        }
        var symbols:Array<String> = []
        for (_,string) in (dataArray?.enumerated())! {
            let infor = string.replacingOccurrences(of: "/", with: "_")
            if infor.count != 0 {
                symbols.append(infor)
            }
        }
        
        var tickServer = ServerTick()
        tickServer.symbols = symbols
        SocketManager.shared.subscribe(server: tickServer)
//        SocketManager.shared.delegate = delegate as? SocketManagerDelegate
    }

    /// 取消订阅
    func cancelSubscribe(key:String) {
        if key.count == 0 {
            return
        }
        
        let dataArray = pairName[key]
        if (dataArray?.count)! <= 0 {
            return
        }
        var symbols:Array<String> = []
        for (_,string) in (dataArray?.enumerated())! {
            let infor = string.replacingOccurrences(of: "/", with: "_")
            if infor.count != 0 {
                symbols.append(infor)
            }
        }
        var tickServer = ServerTick()
        tickServer.symbols = symbols
        SocketManager.shared.cancelSubscribe(server: tickServer)
        
    }
    
    
    /// 订阅单币种对
    ///
    /// - Parameter pairName: 币种对名称
    func subscribeSingleCurrency(pairName:String) {
        if pairName.count == 0 {
            return
        }
        var symbols:Array<String> = []
        let infor = pairName.replacingOccurrences(of: "/", with: "_")
        if infor.count == 0 {
            return
        }
        symbols.append(infor)
        var tickServer = ServerTick()
        tickServer.symbols = symbols
        SocketManager.shared.subscribe(server: tickServer)
        
    }
    
    func cancelScribeSingleCurrency(pairName:String)  {
        if pairName.count == 0 {
            return
        }
        var symbols:Array<String> = []
        let infor = pairName.replacingOccurrences(of: "/", with: "_")
        if infor.count == 0 {
            return
        }
        symbols.append(infor)
        var tickServer = ServerTick()
        tickServer.symbols = symbols
        SocketManager.shared.cancelSubscribe(server: tickServer)
    }
    
    func searchCoinPair(key:String) -> [String] {
        if key.count == 0 {
            return []
        }
        let newKey = key.uppercased()
        if historyPairName[newKey] != nil {
        let arr:[String] = historyPairName[newKey]!
        return arr
        }else {
            return []
        }
    }
    
    
    /// 获取选择title名称
    ///
    /// - Returns: 名称数组
    func archiveTitleArray() -> [String] {
        if self.sysmbols.count == 0 {
            return []
        }
        return self.sysmbols
    }
    
    
    /// 更新数据源
    ///
    /// - Parameter data: socket数据源
    func updateParameters(data: [String:Any])  {
        //多交易对
        if let tickdata = data["datas"] as? [[String:Any]] {
            if let _ = data["symbols"] as? [String] {
                for tickData in tickdata {
                    self.updateSignalTick(tickData: tickData)
                }
            }
            
        }
        //单交易对
        if let tickData = data["data"] as? [String:Any] {
            if let symbol = data["symbol"] as? String {
                self.updateSignalTick(tickPair:symbol,tickData: tickData)
            }
        }
   }
    
    
    
    private func updateSignalTick(tickPair:String = "",tickData:[String:Any]) {
        var symbol = ""
        if tickPair.count == 0 {
            if (tickData["symbol"] as? String) != nil {
                symbol = tickData["symbol"]! as! String
            }
        }else {
            symbol = tickPair
        }
        if symbol.count == 0 {
            return
        }
        symbol = symbol.replacingOccurrences(of: "_", with: "/")
        guard let code:String = (symbol as NSString).components(separatedBy: "/").last else {
            return
        }
        let dataArray = self.pairDic[code]
        let open = tickData["day_open"] as? Double
        let vol = tickData["day_volume"] as? Double
        let price = tickData["price"] as? Double
        let ts = tickData["ts"] as? Double
        let amount = tickData["amount"] as? Double
        
        let strs = symbol.components(separatedBy: "/")
        let money = Double(CYCalculate.cy_multiplying(firstNumber: AppContext.default.getExTick(symbol: strs.last ?? ""), lastNumber:price!, digit: 8))!
        
        if dataArray == nil {return}
        
        for (_,model) in dataArray!.enumerated() {
            if self.selectPairModel.name == symbol {
                self.selectPairModel.open = open ?? 0
                self.selectPairModel.vol = vol ?? 0
                self.selectPairModel.price = price ?? 0
                self.selectPairModel.money = money
                self.selectPairModel.ts = ts ?? 0
                self.selectPairModel.amount = amount ?? 0
            }
            if model.name == symbol {
                model.open = open ?? 0
                model.vol = vol ?? 0
                model.price = price ?? 0
                model.money = money
                model.ts = ts ?? 0
                model.amount = amount ?? 0
                break
            }
        }
    }
}
extension APPTransactionPair: RequestCallBack,RequestDataReformer,RequestParamSource {
    
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        dPrint(data!)
        self.sysmbols = []
        isRequestIng = false
        isRequestFail =  false
        failNumber = 0
        if let _ = request as? MarketCoinRequest {
            if let sysmbols = data!["data"] as? [[String:[Any]]] {
                for (i,dic)  in  sysmbols.enumerated() {
                    for (index,dataArr) in dic.values.enumerated() {
                       let key = Array(dic.keys)[index]
                        if key.count == 0 {
                            break
                        }
                       self.sysmbols.append(key)
                        var nameArr:[String] = []
                        var historyArr:[String] = []
                        var suportCoinArr:[String] = []
                        var infoArr:[CoinRegularModel] = []
                        for info in dataArr {
                            if  ((info as? [String:Any]) != nil) {
                               let model = CoinRegularModel(JSON: info as! [String:Any])
                                historyArr.append(model?.tradeCode ?? "")
                                if model?.tradeStatus == 0 {
                                    nameArr.append(model?.tradeCode ?? "")
                                }
                                //判断支持币币交易
                                if model?.tradeStatus == 0 && model?.conventionLock == 0 {
                                    suportCoinArr.append(model?.tradeCode ?? "")
                                    infoArr.append(model!)
                                }
                            }
                        }
                       coinPairInfo.updateValue(infoArr, forKey: key)
                       historyPairName.updateValue(historyArr, forKey: key)
                        coinPairName.updateValue(suportCoinArr, forKey: key)
                        //当前开放的币种
                       pairName.updateValue(nameArr, forKey: key)
                        self.updateCoinInfo(nameArr: nameArr, isSupportCoin: false, index: index, i: i, key: key)
                        self.updateCoinInfo(nameArr: suportCoinArr, isSupportCoin: true, index: index, i: i, key: key)
                    }
                }
                
                if delegate != nil && ((delegate?.requestSuccess) != nil) {
                    delegate?.requestSuccess!(data)
                }

            }
        }
    }
    
    func updateCoinInfo(nameArr:[String],isSupportCoin:Bool,index:Int,i:Int,key:String) {
        var dataArray: [MarketCoinModel] = []
        for (position,name) in nameArr.enumerated() {
            let model = MarketCoinModel()
            if isSupportCoin {
            //默认选中第一个
            if index == 0 && position == 0 && i == 0 {
                selectPairModel = model
                leverPairModel = model
            }
          }
            model.name = name
            dataArray.append(model)
        }
        if isSupportCoin {
            coinPairDic.updateValue(dataArray, forKey: key)
        }else {
        pairDic.updateValue(dataArray, forKey:key)
            
        }
    }
    
    /// 校验当前币对是否支持币币交易
    ///
    /// - Parameter name: 币对名称
    /// - Returns: 结果
    func checkCurrentIsSupportCoin(name:String) -> Bool {
        if name.components(separatedBy: "/").count < 2 {
            return false
        }
        let key = name.components(separatedBy: "/").last
        let coinNameArr = coinPairInfo[key ?? ""]
        if coinNameArr == nil {
            return false
        }
        for model in coinNameArr! {
            if model.tradeCode == name {
                return true
            }
        }
        return false
    }
    
    
    /// 获取币对交易规则
    ///
    /// - Parameter name: 币对名称
    /// - Returns: 规则model
    func archiveCoinPairRegular(name:String) -> CoinRegularModel {
        if name.components(separatedBy: "/").count < 2 {
            return CoinRegularModel()
        }
        let key = name.components(separatedBy: "/").last
        let regualerArr = coinPairInfo[key ?? ""]
        if regualerArr == nil {
            return CoinRegularModel()
        }
        for model in regualerArr! {
            if model.tradeCode == name {
                return model
            }
        }
        return CoinRegularModel()
    }


    func requestDidSucess(_ request: BaseRequest) {
    }
    
    func requestDidFail(_ request: BaseRequest) {
        isRequestFail  = true
        isRequestIng = false
        failNumber = failNumber + 1
        if let _ = request as? MarketCoinRequest {
            if delegate != nil && ((delegate?.requestFail) != nil) {
                delegate?.requestFail!()
            }
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        let pramas: [String:Any] = [:]
        if let _ = request as? MarketCoinRequest {
        }
        return pramas
    }
    
}

